package com.usc.csci588.chaltrojan.login;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.usc.csci588.chaltrojan.R;
import com.usc.csci588.chaltrojan.ui.main.MainUIMapActivity;

public class UpdateTripDataActivity extends Activity {

	String updatereq;
	String handle;
	String tripId;
	String tripName;

	double destLat, destLong;

	String[] handles;
	double[] lats;
	double[] lngs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.join_trip_form_layout);
		Bundle extras = getIntent().getExtras();
		tripName = extras.getString(Constants.TripName);
		// handle = extras.getString("userHandle");
		SharedPreferences settings = getSharedPreferences("HANDLE", 0);
		handle = settings.getString("handle", "default_user");

		updatereq = generateUpdateRequest(tripName, handle);
		Log.d("join", updatereq);
		new GetUpdatesOfTrip().execute(updatereq);

	}

	public String generateUpdateRequest(String tn, String handle) {
		// http://ec2-23-22-128-131.compute-1.amazonaws.com:8080/ChalTrojan2/GetLocation?tripId=28
		String updateURL = Constants.ChalTrojanHostName;
		updateURL += "/ChalTrojan2/GetLocation?tripId=" + tn;
		updateURL += "&handle=" + handle;
		Log.d("update", "updateURL is --> " + updateURL);
		return updateURL;
	}

	public void gotoMainUI() {

		Intent i = new Intent(getApplicationContext(), MainUIMapActivity.class);
		i.putExtra(Constants.mainUIRequestedFrom,
				Constants.mainUIFromUpdateTrip);
		i.putExtra(Constants.HandleArray, handles);
		i.putExtra(Constants.latArray, lats);
		i.putExtra(Constants.longArray, lngs);
		i.putExtra(Constants.TripName, tripName);
		i.putExtra(Constants.Lat_Lng, new double[] { destLat, destLong });

		Log.d("update", "Arrays Being sent are: handlesArray --> " + handles
				+ " latArray --> " + lats + " longArray --> " + lngs);

		startActivity(i);
		finish();
	}

	private class GetUpdatesOfTrip extends AsyncTask<String, Void, Void> {

		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = ProgressDialog.show(UpdateTripDataActivity.this,
					"Member Information",
					"Fetching member information from the server...");

		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub

			String request = params[0];
			try {

				DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder documentBuilder = documentBuilderFactory
						.newDocumentBuilder();
				Document document = documentBuilder.parse(request);
				Log.d("join", "Got here.");
				NodeList locationList = document.getElementsByTagName("location");
				int len = locationList.getLength();
				Log.d("join", "Location Length is " + len);
				Log.d("join", locationList.toString());
				
				
				if(len == 0)
				{
				handles = null;
				lats = null;
				lngs = null;					
				}
				else
				{
				handles = new String[len];
				lats = new double[len];
				lngs = new double[len];
				
				}
				
				for (int i = 0; i < len; i++) {

					Node node = locationList.item(i);
					Element locationElement = (Element) node;

					NodeList handleList = locationElement
							.getElementsByTagName("handle");
					NodeList latList = locationElement
							.getElementsByTagName("lat");
					NodeList longList = locationElement
							.getElementsByTagName("long");

					Node handle = handleList.item(0);
					Node lat = latList.item(0);
					Node lng = longList.item(0);

					handles[i] = handle.getTextContent();
					lats[i] = Double.parseDouble(lat.getTextContent());
					lngs[i] = Double.parseDouble(lng.getTextContent());

					// Log.d("join",handles[i]+" "+lats[i]+","+ lngs[i]);

				}

				// http://ec2-23-22-128-131.compute-1.amazonaws.com:8080/ChalTrojan2/GetTripDetails?handle=varun&tripName=nycity

				for (int i = 0; i < len; i++) {
					Log.d("join", handles[i] + " " + lats[i] + "," + lngs[i]);
				}

				{					
					String getTripDetailsURL = Constants.ChalTrojanHostName
							+ "/ChalTrojan2/GetTripDetails?handle=" + handle
							+ "&tripName=" + tripName;
					Document tripDetails = documentBuilder.parse(getTripDetailsURL);
					Log.d("update","getTripDetailsURL ==> "+getTripDetailsURL);
					NodeList details = tripDetails.getElementsByTagName("Details");				
					
					Node node = details.item(0);
					Element locationElement = (Element) node;
					NodeList latList = locationElement.getElementsByTagName("lang");
					
					NodeList longList = locationElement.getElementsByTagName("long");
	
					// = handleList.item(0);
					Node lat = latList.item(0);
					Node lng = longList.item(0);
					
					destLat = Double.parseDouble(lat.getTextContent());
					destLong = Double.parseDouble(lng.getTextContent());
					Log.d("update","send data --> "+destLat+" "+destLong);
					
				}
				/*
				 * Node s = successList.item(0); value = s.getTextContent();
				 * Log.d("join", value+"is value");
				 */
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pd.dismiss();
			gotoMainUI();

		}

	}

}
